package edu.nf.project.services.storeOperation.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.nf.project.entitys.entity.storeOperation.convention.operate.RefundRequest;
import edu.nf.project.entitys.enums.storeOperation.RequestStatusEnum;
import edu.nf.project.mappers.storeOperation.convention.RefundRequestMapper;
import edu.nf.project.services.process.RefundProcess;
import edu.nf.project.services.storeOperation.RefundRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author CSY
 * @date 2025 - 06 - 18
 */
@Service
public class RefundRequestServiceImpl implements RefundRequestService {
    @Autowired
    private RefundRequestMapper refundRequestMapper;

    @Autowired
    private Map<String, RefundProcess> refundProcessMap;

    @Override
    public Integer insertRefundRequest(RefundRequest refundRequest) {
        refundRequestMapper.insert(refundRequest);
        return refundRequest.getRrId();
    }

    @Override
    public List<RefundRequest> listRefundRequestByUserId(Integer uId) {
        LambdaQueryWrapper<RefundRequest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RefundRequest::getUId, uId).orderByDesc(RefundRequest::getRequestTime);;
        return refundRequestMapper.selectList(queryWrapper);
    }

    @Override
    public RefundRequest getRefundRequestById(Integer id) {
        return refundRequestMapper.selectById(id);
    }

    @Override
    public void cancelRefundRequestById(Integer rrId) {
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setRrId(rrId);
        refundRequest.setRequestStatus(RequestStatusEnum.CANCEL);
        refundRequestMapper.updateById(refundRequest);
    }

    @Override
    public void updateRefundRequest(RefundRequest refundRequest) {
        refundRequest.setOperateTime(new Date());
        refundRequestMapper.updateById(refundRequest);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processRefund(RefundRequest refundRequest,String refundWay) {
        updateRefundRequest(refundRequest);
        RefundProcess refundProcess = refundProcessMap.get(refundWay);
        refundProcess.refund(refundRequest);
    }
}
